package binds

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"stock/binds/utility/ghttp"
	"stock/binds/utility/tradeDate"
)

var appUrlMaps = map[string]string{
	"市场情绪值": fmt.Sprintf("https://apphis.longhuvip.com/w1/api/index.php?a=DiskReview&apiv=w31&c=HisHomeDingPan&PhoneOSNew=1&DeviceID=00000000-296c-20ad-0000-00003eb74e84&VerSion=5.7.0.12&Day=%s&", tradeDate.GetLatestDay()),
	"大盘直播":  "https://apphwhq.longhuvip.com/w1/api/index.php?a=ZhiBoContent&apiv=w33&c=ConceptionPoint&VerSion=5.14.0.4&PhoneOSNew=1&index=0&DeviceID=ffffffff-b464-04d1-0000-00003643032a&",
}

// App struct
type App struct {
	ctx context.Context
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{}
}

// startup is called at application startup
func (a *App) Startup(ctx context.Context) {
	// Perform your setup here
	a.ctx = ctx
}

// domReady is called after front-end resources have been loaded
func (a App) DomReady(ctx context.Context) {
	// Add your action here
}

// beforeClose is called when the application is about to quit,
// either by clicking the window close button or calling runtime.Quit.
// Returning true will cause the application to continue, false will continue shutdown as normal.
func (a *App) BeforeClose(ctx context.Context) (prevent bool) {
	return false
}

// shutdown is called at application termination
func (a *App) Shutdown(ctx context.Context) {
	// Perform your teardown here
}

// Greet returns a greeting for the given name
func (a *App) Greet(name string) string {
	return fmt.Sprintf("Hello %s, It's show time!", name)
}
func (a *App) LoadStockData(action string) string {

	httpClient := ghttp.GetClient()
	actionUrl, ok := appUrlMaps[action]
	if ok {
		//proxyURL, _ := url.Parse("http://localhost:8888")
		//http.DefaultTransport.(*http.Transport).Proxy = http.ProxyURL(proxyURL)
		response, err := httpClient.Get(context.TODO(), actionUrl)
		if err != nil {
			log.Println(actionUrl)
			log.Println(err.Error())
			errJson, _ := json.Marshal(map[string]string{
				"msg":     err.Error(),
				"errcode": "-1",
			})
			return string(errJson)
		}
		defer response.Body.Close()
		body, err := io.ReadAll(response.Body)
		if err != nil {
			errJson, _ := json.Marshal(map[string]string{
				"msg":     err.Error(),
				"errcode": "-1",
			})
			return string(errJson)
		}
		return string(body)
	}
	errJson, _ := json.Marshal(map[string]string{
		"msg":     "not found url",
		"errcode": "-1",
	})
	return string(errJson)
}
